package com.Sun.console;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Pattern;

import com.Sun.DB.DBHelper;
import com.Sun.Helper.addNewFileHelper;
import com.Sun.Helper.buildIndexTreeHelper;
import com.Sun.Helper.deleteFileHelper;
import com.Sun.Model.encryptedIndex;
import com.Sun.Model.fileScorePair;
import com.Sun.Model.indexTree;
import com.Sun.Model.indexTreeNode;
import com.Sun.Model.pathInfo;
import com.Sun.index.buildIndex;
import com.Sun.index.indexEncrypted;
import com.Sun.serialize.objectSerializeUtil;
import com.sun.TrapDoor.GenTropDoor;

public class MainConsole {
	public static void main(String[]args)
	{
		boolean flag=true;
		String strChose="";
		int chose=-1;
		int mostK=20;
		indexTree searchIndexTree=null;
		Pattern pattern = Pattern.compile("[0-9]*");
		while(flag)
		{
			System.out.println("------Sun动态多关键字加密搜索方案性能测试------");
			System.out.println("1.文件上传（生成加密索引树相关功能）");
			System.out.println("2.多关键字搜索");
			System.out.println("3.删除文件");
			System.out.println("4.添加文件");
			System.out.println("5.退出");
			Scanner scanner=new Scanner(System.in);
			strChose=scanner.next();
			if(pattern.matcher(strChose).matches())
			{
				chose=Integer.parseInt(strChose);
				switch (chose) {
				case 1:
				{
					indexEncrypted inSK=buildIndex.getEncryptedSK();
					List<String>fileNameList=DBHelper.getAllFileName();
					System.out.println("······开始构建加密索引······");
					long startTime=System.currentTimeMillis();
					Queue<indexTreeNode> queue=buildIndexTreeHelper.getallLeafIndexTree(fileNameList);
					if(searchIndexTree==null)
					{
						searchIndexTree=new indexTree();
					}
					searchIndexTree.buildBalanceBinTree(queue);
					buildIndexTreeHelper.encrypteTreeNode(searchIndexTree.getRoot(), inSK);
				    long endTime=System.currentTimeMillis();
				    System.out.println("构建索引树的时间是："+(endTime-startTime));
				    try {
						objectSerializeUtil.serialize(searchIndexTree.getRoot(), "root.obj");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				    inSK=null;
				    break;
				}
				case 2:
				{
					System.out.println("请输入你要搜索的关键字(输入exit表示结束)：");
					Scanner scWordInput=new Scanner(System.in);
					List<String> searchWordList=new ArrayList<String>();
					String line = "";
			        while (scWordInput.hasNextLine()) {
			            line = scWordInput.nextLine();
			            if ("exit".equals(line)) {
			                break;
			            }
			            if(DBHelper.isWordExists(line))
			            {
			            	searchWordList.add(line);
			            }
			            else {
							System.out.println("输入关键字无效，请重新输入：");
						}
			        }
//					List<String> searchWordList=new ArrayList<String>();
//					try {
//						BufferedReader bf=new BufferedReader(new FileReader("searchWord.txt"));
//						String tempWord=null;
//						while((tempWord=bf.readLine())!=null)
//						{
//							if(DBHelper.isWordExists(tempWord))
//							{
//								searchWordList.add(tempWord);
//							}
//							else
//							{
//								System.out.println(tempWord+"不是关键");
//							}
//						}
//						bf.close();
//					} catch (FileNotFoundException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
			        System.out.println("请输入想获取文件的个数：");
				     mostK=scWordInput.nextInt();
			        encryptedIndex trapDoor=GenTropDoor.getTropDoor(searchWordList);
						try {
							indexTreeNode root=(indexTreeNode) objectSerializeUtil.deserialize("root.obj");
							searchIndexTree=new indexTree(root);
						} catch (IOException e) {
							e.printStackTrace();
						}
					System.out.println("······多关键字搜索开始······");
					long  startTime=System.currentTimeMillis();
			    	List<fileScorePair> reFiles=searchIndexTree.searchOverTree(searchIndexTree.getRoot(), trapDoor, mostK);
			    	System.out.println("最相关的"+mostK+"个文件为：");
			    	for(int i=0;i<reFiles.size();i++)
			    	{
			    		System.out.println(reFiles.get(i).getFileName()+":"+reFiles.get(i).getScore());
			    	}
			    	long endTime=System.currentTimeMillis();
				     System.out.println("搜索过程用的时间是："+(endTime-startTime)+"ms");
					 System.out.println("······多关键字搜索结束······");
					break;
				}
				case 3:
				{
					System.out.println("请输入要删除的文件名称：");
					Scanner deleteScanner=new Scanner(System.in);
					String fileName=deleteScanner.next();
					if(DBHelper.isFileExits(fileName))
					{
						indexEncrypted inSK=buildIndex.getEncryptedSK();
						indexTreeNode root;
						try {
							root = (indexTreeNode) objectSerializeUtil.deserialize("root.obj");
							indexTree searchTree=new indexTree(root);
							int dflag=DBHelper.deleteFileNameOnly(fileName);
							if(dflag>0)
							{
								System.out.println("数据库中的相关条目删除成功！");
							}
							long startTime=System.currentTimeMillis();
							indexTreeNode deleteNode=searchTree.getLeafNodeByFileName(root, fileName);
							System.out.println("测试："+deleteNode.getFID());
							Stack<pathInfo>pathStack=deleteFileHelper.getPathInfos(root, deleteNode,inSK);//得到节点更新的路径
							inSK=null;
							int f=deleteFileHelper.updateTreeByPath(root, pathStack);//根据路径更新服务器端索引树
							if(f>0)
							{
								System.out.println("更新索引树成功！");
							}
							long endTime=System.currentTimeMillis();
							System.out.println("删除操作的总时间是："+(endTime-startTime)+"ms");
							objectSerializeUtil.serialize(root, "root.obj");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					else{
						System.out.println("要删除的文件不存在！");
					}
					break;
				}
				case 4:
				{
					System.out.println("请输入您要添加的文件的路径名称：");
					Scanner newFileScanner=new Scanner(System.in);
					String filePath=newFileScanner.next();
					String fileName=addNewFileHelper.getReFileName(filePath);
						indexEncrypted inSK=buildIndex.getEncryptedSK();
						indexTreeNode root;
						try {
							root = (indexTreeNode) objectSerializeUtil.deserialize("root.obj");
							indexTree searchTree=new indexTree(root);
							long startTime=System.currentTimeMillis();
							indexTreeNode newFileNode=buildIndexTreeHelper.getNewLeafIndexTree(fileName);
							indexTreeNode changedNode=searchTree.getChangedNode(root);
							System.out.println("test changeNode is"+changedNode.getFID());
							indexTreeNode newTempNode=searchTree.getNewNode(changedNode,newFileNode);//新节点为右孩子
							if(changedNode.getParent().getLeft()==changedNode)
							{
								changedNode.getParent().setLeft(newTempNode);
							}
							else {
								changedNode.getParent().setRight(newTempNode);
							}
							newTempNode.setParent(changedNode.getParent());
							changedNode.setParent(newTempNode);
							newFileNode.setParent(newTempNode);//将新的节点加入到二叉搜索树中 
							Stack<pathInfo>pathStack=addNewFileHelper.getPathInfos(root, newFileNode,inSK);//得到节点更新的路径
							inSK=null;
							long startTime1=System.currentTimeMillis();
							int f=addNewFileHelper.updateTreeByPath(root, pathStack);//根据路径更新服务器端索引树
							long endTime=System.currentTimeMillis();
							System.out.println("添加新文件操作的时间为："+(endTime-startTime));
							System.out.println("根据路径更新服务端的时间为："+(endTime-startTime1));
							objectSerializeUtil.serialize(root, "root.obj");
							
					}catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				}
				case 5:
				{
					flag=false;
					break;
					
				}
				default:
					break;
				}
			}
			else {
				System.out.println("输入的不是整数，请重新输入！");
			}
	}
}
}
